package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActGoodDetailBsdLVAdapter;
import com.landeb.shop.huo.adapter.ActGoodDetailFragAdapter;
import com.landeb.shop.huo.adapter.SkuAdapter;
import com.landeb.shop.huo.bean.BeanGoodDetailActBsd;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.eventMsg.MsgResetGoodsFrag;
import com.landeb.shop.huo.frag.CommentFragActGoodDetail;
import com.landeb.shop.huo.frag.DetailFragActGoodDetail;
import com.landeb.shop.huo.frag.GoodFragActGoodDetail;
import com.landeb.shop.huo.httpRequest.ActGoodsDetailRequest;
import com.landeb.shop.huo.view.SkuView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class GoodDetailActivity extends BaseActivity implements View.OnClickListener, ActGoodDetailBsdLVAdapter.OnSelectFinishedListener {

    private Button btnBuy, btnAddToCart;
    private LinearLayout btnBack;
    private LinearLayout llFocus, llToCart, llToShop;
    private ImageView ivFocus;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private List<String> mTabList;
    private List<Fragment> mFragList;
    private FragmentManager mFragManager;
    private ActGoodDetailFragAdapter mAdapter;
    private GoodFragActGoodDetail mGoodFrag;
    private DetailFragActGoodDetail mDetailFrag;
    private CommentFragActGoodDetail mCommentFrag;

    private String mID;
    private String mTitle;
    private String mPrice;

    private String mUrl;
    private Retrofit mRetrofit;
    private ActGoodsDetailRequest mRequest;
    private boolean isFocused;
    private boolean isUpdatingFocus = false;

    private int amount = 1;
    private String attrs;

    public static void toAct(Context context) {
        Intent intent = new Intent(context, GoodDetailActivity.class);
        context.startActivity(intent);
    }

    public static void toAct(Context context, String id) {
        Intent intent = new Intent(context, GoodDetailActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    public static void toAct(Context context, String id, String title, String price) {
        Intent intent = new Intent(context, GoodDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("title", title);
        intent.putExtra("price", price);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_good_detail);

        Intent intent = getIntent();
        mID = intent.getStringExtra("id");
        mTitle = intent.getStringExtra("title");
        mPrice = intent.getStringExtra("price");

        Log.e("onCreate: ", "id++++++++++++++++++++" + mID);

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActGoodsDetailRequest.class);


        initView();
        initData();
        initEvent();

        refresh();

    }

    private void initEvent() {
        btnBack.setOnClickListener(this);
        llFocus.setOnClickListener(this);
        btnBuy.setOnClickListener(this);
        btnAddToCart.setOnClickListener(this);

        llToCart.setOnClickListener(this);
        llToShop.setOnClickListener(this);

    }

    private void initData() {

        mTabList = new ArrayList<>();
        mTabList.add("商品");
        mTabList.add("详情");
        mTabList.add("评价");

        mFragList = new ArrayList<>();
        // TODO: 2016/10/26 修改载入的frag
        mGoodFrag = GoodFragActGoodDetail.newInstance("", mID, mTitle, mPrice);
        mDetailFrag = DetailFragActGoodDetail.newInstance("", mID);
        mCommentFrag = CommentFragActGoodDetail.newInstance("",mID);
        mFragList.add(mGoodFrag);
        mFragList.add(mDetailFrag);
        mFragList.add(mCommentFrag);

        mFragManager = getSupportFragmentManager();
        mAdapter = new ActGoodDetailFragAdapter(mFragManager, mTabList, mFragList);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);

    }

    private void initView() {
        btnBack = (LinearLayout) findViewById(R.id.act_good_detail_btn_back);

        mTabLayout = (TabLayout) findViewById(R.id.act_good_detail_tab);
        mViewPager = (ViewPager) findViewById(R.id.act_good_detail_viewPager);

        llFocus = (LinearLayout) findViewById(R.id.act_good_detail_ll_focus);
        ivFocus = (ImageView) findViewById(R.id.act_good_detail_iv_focus);
        btnBuy = (Button) findViewById(R.id.act_good_detail_btn_buy_now);
        btnAddToCart = (Button) findViewById(R.id.act_good_detail_btn_add_to_cart);

        llToCart = (LinearLayout) findViewById(R.id.act_good_detail_ll_goToCart);
        llToShop = (LinearLayout) findViewById(R.id.act_good_detail_ll_goToShop);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.act_good_detail_btn_back:
                // TODO: 2016/11/19 返回键
                onBackPressed();
                break;

            case R.id.act_good_detail_ll_focus:
                // TODO: 2016/11/19 关注
                if (isFocused) {

                    if (!isUpdatingFocus) {

                        mRequest.cancelFavourite(mID)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<BeanStatusInfo>() {
                                    @Override
                                    public void onCompleted() {
                                        Log.e("cancelFavourite", "onCompleted: ");

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Log.e("cancelFavourite", "onError: " + e.toString());

                                    }

                                    @Override
                                    public void onNext(BeanStatusInfo beanStatusInfo) {

                                        if (beanStatusInfo.getStatus() == 1) {
                                            setUnfocused();
                                        } else {
                                            Toast.makeText(GoodDetailActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                                        }

                                    }
                                });

                    }

                } else {

                    mRequest.addFavourite(mID)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Subscriber<BeanStatusInfo>() {
                                @Override
                                public void onCompleted() {
                                    Log.e("addFavourite", "onCompleted: ");

                                }

                                @Override
                                public void onError(Throwable e) {
                                    Log.e("addFavourite", "onError: " + e.toString());

                                }

                                @Override
                                public void onNext(BeanStatusInfo beanStatusInfo) {

                                    if (beanStatusInfo.getStatus() == 1) {
                                        setFocused();
                                    } else {
                                        Toast.makeText(GoodDetailActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });

                }


                break;

            case R.id.act_good_detail_btn_buy_now:
                // TODO: 2016/11/19  立即购买
//                showSku();

//                fixedShowSku();
                Log.e( "立即购买mid",mID );


                mRequest.GoodsAdd(mID, null, 1,"1")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanStatusInfo>() {
                            @Override
                            public void onCompleted() {
                                Log.e("GoodsAdd", "onCompleted: ");
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("GoodsAdd", "onError: " + e.toString());

                            }

                            @Override
                            public void onNext(BeanStatusInfo beanStatusInfo) {

                                if (beanStatusInfo.getStatus() == 1) {
                                    Toast.makeText(GoodDetailActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();

                                    MainActivity.toAct(GoodDetailActivity.this, MainActivity.CART_PAGE);


                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(GoodDetailActivity.this);
                                    builder.setTitle("系统提示")
                                            .setMessage(beanStatusInfo.getInfo())
                                            .setPositiveButton("确定", null)
                                            .setCancelable(false)
                                            .show();
                                }

                            }
                        });
                break;

            case R.id.act_good_detail_btn_add_to_cart:
                // TODO: 2016/11/19  加入购物车
                Log.e( "加入购物车mid",mID );


                mRequest.GoodsAdd(mID, null, 1,"")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanStatusInfo>() {
                            @Override
                            public void onCompleted() {
                                Log.e("GoodsAdd", "onCompleted: ");
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("GoodsAdd", "onError: " + e.toString());

                            }

                            @Override
                            public void onNext(BeanStatusInfo beanStatusInfo) {

                                if (beanStatusInfo.getStatus() == 1) {
                                    Toast.makeText(GoodDetailActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(GoodDetailActivity.this);
                                    builder.setTitle("系统提示")
                                            .setMessage(beanStatusInfo.getInfo())
                                            .setPositiveButton("确定", null)
                                            .setCancelable(false)
                                            .show();
                                }

                            }
                        });

                break;

            case R.id.act_good_detail_ll_goToCart:
                // TODO: 2016/11/19  去购物车

                MainActivity.toAct(GoodDetailActivity.this, MainActivity.CART_PAGE);
                break;

            case R.id.act_good_detail_ll_goToShop:
                // TODO: 2016/11/19  去店铺

                ShopDetailActivity.toAct(this, GoodFragActGoodDetail.mShopId);

                break;

        }

    }

    private void refresh() {

        mRequest.getFocused(mID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanStatusInfo>() {
                    @Override
                    public void onCompleted() {

                        Log.e("getFocused", "onCompleted: ");

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("getFocused", "onError: " + e.toString());

                    }

                    @Override
                    public void onNext(BeanStatusInfo beanStatusInfo) {

                        if (beanStatusInfo.getStatus() == 1) {
                            setFocused();
                        } else {
                            setUnfocused();
                        }

                    }
                });
    }

    private void setFocused() {

        isFocused = true;
        ivFocus.setImageResource(R.drawable.details_attention_select);
//        Toast.makeText(GoodDetailActivity.this,"关注了",Toast.LENGTH_SHORT).show();
    }

    private void setUnfocused() {

        isFocused = false;
        ivFocus.setImageResource(R.drawable.details_attention_unselect);

//        Toast.makeText(GoodDetailActivity.this,"取消了",Toast.LENGTH_SHORT).show();

    }


    private void showSku() {

        amount = 1;

        String text = "{\"status\":1,\"info\":\"\\u6210\\u529f\",\"data\":{\"attrs\":[{\"id\":\"1\",\"name\":\"\\u53e3\\u5473\",\"child\":[{\"id\":\"11\",\"name\":\"\\u4e0d\\u8fa3\",\"is_select\":\"0\"},{\"id\":\"12\",\"name\":\"\\u5fae\\u8fa3\",\"is_select\":\"0\"},{\"id\":\"13\",\"name\":\"\\u4e2d\\u8fa3\",\"is_select\":\"0\"},{\"id\":\"14\",\"name\":\"\\u91cd\\u8fa3\",\"is_select\":\"0\"}]},{\"id\":\"2\",\"name\":\"\\u4efd\\u91cf\",\"child\":[{\"id\":\"21\",\"name\":\"10g\\u88c5\",\"is_select\":\"0\"},{\"id\":\"22\",\"name\":\"20g\\u88c5\",\"is_select\":\"0\"},{\"id\":\"23\",\"name\":\"50g\\u88c5\",\"is_select\":\"0\"},{\"id\":\"24\",\"name\":\"80g\\u88c5\",\"is_select\":\"0\"},{\"id\":\"25\",\"name\":\"100g\\u88c5\",\"is_select\":\"0\"},{\"id\":\"26\",\"name\":\"200g\\u88c5\",\"is_select\":\"0\"}]},{\"id\":\"3\",\"name\":\"\\u6570\\u91cf\",\"child\":[{\"id\":\"31\",\"name\":\"10\\u888b\",\"is_select\":\"0\"},{\"id\":\"32\",\"name\":\"20\\u888b\",\"is_select\":\"0\"},{\"id\":\"33\",\"name\":\"30\\u888b\",\"is_select\":\"0\"},{\"id\":\"34\",\"name\":\"40\\u888b\",\"is_select\":\"0\"},{\"id\":\"35\",\"name\":\"50\\u888b\",\"is_select\":\"0\"},{\"id\":\"36\",\"name\":\"60\\u888b\",\"is_select\":\"0\"}]}],\"stocks\":[{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"},{\"attr\":\"11,21,31\",\"price\":\"100\",\"stock\":\"10\"}]}}";
        Gson gson = new Gson();
        List<BeanGoodDetailActBsd.DataBean.AttrsBean> testList = gson.fromJson(text, BeanGoodDetailActBsd.class).getData().getAttrs();
        List<BeanGoodDetailActBsd.DataBean.StocksBean> stocksBeanList = gson.fromJson(text, BeanGoodDetailActBsd.class).getData().getStocks();

        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);

        View dialogView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog_sku, null);

        ImageView dialogIv = (ImageView) dialogView.findViewById(R.id.iv_bottom_sheet_dialog_sku);
        TextView dialogPrice = (TextView) dialogView.findViewById(R.id.tv_price_bottom_sheet_dialog_sku);
        TextView dialogStock = (TextView) dialogView.findViewById(R.id.tv_stock_bottom_sheet_dialog_sku);
        TextView dialogDes = (TextView) dialogView.findViewById(R.id.tv_des_bottom_sheet_dialog_sku);
        Button dialogBtnBuyNow = (Button) dialogView.findViewById(R.id.btn_buyNow_bottom_sheet_dialog_sku);
        Button dialogBtnToCart = (Button) dialogView.findViewById(R.id.btn_toCart_bottom_sheet_dialog_sku);

        Button dialogBtnAdd = (Button) dialogView.findViewById(R.id.btn_amountAdd_bottom_sheet_dialog_sku);
        Button dialogBtnDecrease = (Button) dialogView.findViewById(R.id.btn_amountDecrease_bottom_sheet_dialog_sku);
        final TextView dialogAmount = (TextView) dialogView.findViewById(R.id.tv_amount_bottom_sheet_dialog_sku);

        final ListView dialogLv = (ListView) dialogView.findViewById(R.id.lv_bottom_sheet_dialog_sku);


        dialogBtnBuyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2016/12/7 立即购买
                bottomSheetDialog.dismiss();
            }
        });

        dialogBtnToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2016/12/7 加入购物车
                bottomSheetDialog.dismiss();
            }
        });

        ActGoodDetailBsdLVAdapter mAdapter = new ActGoodDetailBsdLVAdapter(this, testList, stocksBeanList, dialogPrice, dialogStock, dialogDes);
        mAdapter.setOnSelectFinshedListener(this);
        dialogLv.setAdapter(mAdapter);
        dialogLv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        dialogLv.requestDisallowInterceptTouchEvent(true);
                        break;

                    case MotionEvent.ACTION_UP:


                    case MotionEvent.ACTION_CANCEL:
                        dialogLv.requestDisallowInterceptTouchEvent(false);
                        break;
                }

                return false;
            }
        });

        dialogAmount.setText(amount + "");
        dialogBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                amount++;
                dialogAmount.setText(amount + "");
            }
        });

        dialogBtnDecrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (amount == 1) {
                    return;
                }
                amount--;
                dialogAmount.setText(amount + "");


            }
        });


        bottomSheetDialog.setContentView(dialogView);

        bottomSheetDialog.show();


    }

    private void fixedShowSku() {

//        SkuAdapter s = new SkuAdapter(R.layout.item_act_search_grid_view, mTabList);
//        s.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Log.e("onItemClick: ", mTabList.get(position));
//            }
//        });
//        SkuView<SkuAdapter> skuView = new SkuView<>(this, "url", "title", "desc", "price",
//                s, 8, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        }, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//
//
//        skuView.show();
    }

    @Override
    public void onFinished(String attrs) {
        this.attrs = attrs;
        Toast.makeText(this, "attrs=" + attrs + "amount=" + amount, Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.e("onNewIntent: ", "xxxxxxxxxxxxxxxxxxxxx");

        MsgResetGoodsFrag msg = new MsgResetGoodsFrag();
        msg.setMid(intent.getStringExtra("id"));

        EventBus.getDefault().post(msg);


    }
}
